<script setup lang="ts">
import type { Video } from "~/composables/apis/types/video";
import type { IPlayerOptions } from "xgplayer/es/player";
import type { SwipeInstance } from "vant";
import type Player from "xgplayer";

type SerialExtend = Video.Serial & {
  url: string;
  cover: string;
  lock: boolean;
  isPlay: boolean;
};

const route = useRoute();
const XgVideoRef = ref<{
  playNext: (config: IPlayerOptions) => void;
  pause: () => void;
  switchURL: (url: string) => void;
  getIsActive: () => boolean;
  getPlayer: () => Player;
}>();
const swipeRef = ref<SwipeInstance>();
const vid = route.params.id as string;
const videoApi = useVideoApi();
const videoList = ref<SerialExtend[]>([]);
const currentIndex = ref(0);
const currentVideo = computed(() => videoList.value[currentIndex.value]);
const showEpisodePanel = ref(false);
const showVideoControlList = ref(false);
// 初始化地址
const initVideoUrl = ref("");
const initVideoCover = ref("");

let loadingToast: { close: () => void };
let loadingToastTimer = null;

const playNext = async () => {
  loadingToastTimer = setTimeout(() => {
    loadingToast = showLoadingToast({ duration: 0 });
  }, 0);

  try {
    await getSerialInfo();

    clearTimeout(loadingToastTimer);
    // XgVideoRef.value?.getPlayer?.().blur();
    // 播放下一集
    XgVideoRef.value?.playNext({
      url: videoList.value[currentIndex.value].url,
      poster: currentVideo.value.cover,
    });
    // XgVideoRef.value?.switchURL(videoList.value[currentIndex.value].url);
  } catch (e) {
    loadingToast?.close?.();
  }
};

const handleChange = (index: number) => {
  currentIndex.value = index;

  playNext();

  setLocalPlayletInfo({
    [vid]: keepingFields(currentVideo.value, ["name", "playletId", "id"]),
  });
};

const setTeleportEl = (index: number) => {
  nextTick(() => {
    const selectStr = `.van-swipe-item:nth-child(${index + 1})`;
    const box = document.querySelector<HTMLDivElement>(selectStr);
    const video = document.querySelector<HTMLDivElement>(".video-wrapper");
    video!.style.position = "absolute";
    video!.style.left = "0px";
    video!.style.top = "0px";
    // video!.style.zIndex = "2";
    box?.appendChild(video!);
  });
};

const getSerialInfo = async () => {
  if (!currentVideo.value.url) {
    try {
      const url = await videoApi.serialInfo(
        videoList.value[currentIndex.value].id.toString(),
      );

      if (url) {
        videoList.value[currentIndex.value].url = url;

        if (!initVideoUrl.value) {
          initVideoUrl.value = url;
          initVideoCover.value = videoList.value[currentIndex.value].cover;
        }
      } else {
        showDialog({ title: "Error" });
      }
    } catch (e) {
      XgVideoRef.value?.pause?.();
      showDialog({ title: "Error" });
      // @ts-ignore
      throw new Error(e);
    }
  }
};

// 必须在这个时候再设置位置，否则会产生黑场
const handleLoadeddata = () => {
  setTimeout(() => {
    // 请注意：这里的 currentIndex 一定要设置对
    setTeleportEl(currentIndex.value);
    loadingToast?.close?.();
  }, 300);
};

const visibilitychangeHandler = () => {
  if (document.visibilityState === "hidden") {
    XgVideoRef.value?.pause?.();
  }
};

const handleClick = (e: any, player: Player) => {
  showVideoControlList.value = player.isActive;
};

const handleClickEpisode = (item: never, index: number) => {
  swipeRef.value?.swipeTo(index, { immediate: true });
};

const handleEnded = () => {
  swipeRef.value?.next();
};

onMounted(() => {
  loadingToast = showLoadingToast({ duration: 0 });

  videoApi.serialList(vid).then(async (list) => {
    videoList.value = list.map((it, index) =>
      Object.assign(it, {
        url: "",
        cover: getCoverImg(vid, index.toString()),
        lock: !!it.needLock,
        isPlay: false,
      }),
    );

    const localPlayletInfo = getLocalPlayletInfo();
    if (localPlayletInfo) {
      const currentVideo = localPlayletInfo[vid];
      if (currentVideo && currentVideo.id) {
        const index = videoList.value.findIndex(
          (it) => it.id == currentVideo.id,
        );
        if (index !== -1) {
          currentIndex.value = index;
        }
      }
    }
    console.log("执行?????", currentIndex.value);
    if (currentIndex.value > 0) {
      swipeRef.value?.swipeTo(currentIndex.value, { immediate: true });
    } else {
      getSerialInfo();
    }
  });

  document.addEventListener("visibilitychange", visibilitychangeHandler);
});

onUnmounted(() => {
  document.removeEventListener("visibilitychange", visibilitychangeHandler);
});
</script>

<template>
  <div class="index-page">
    <van-swipe
      ref="swipeRef"
      class="my-swipe"
      vertical
      :show-indicators="false"
      :loop="false"
      @change="handleChange"
    >
      <van-swipe-item v-for="(item, index) in videoList">
        <img
          v-if="Math.abs(currentIndex - index) <= 1"
          class="cover"
          :src="item.cover"
          alt=""
        />
      </van-swipe-item>
    </van-swipe>
    <ClientOnly>
      <XgVideo
        v-if="initVideoUrl"
        ref="XgVideoRef"
        :url="initVideoUrl"
        :init-poster="initVideoCover"
        @loadeddata="handleLoadeddata"
        @error="handleLoadeddata"
        @ended="handleEnded"
        @click="handleClick"
        @blur="showVideoControlList = false"
      />
    </ClientOnly>
    <EpisodePanel
      v-if="videoList && videoList.length > 0"
      v-model:show="showEpisodePanel"
      :list="videoList"
      :title="currentVideo?.playletName"
      :current-index="currentIndex"
      @clickEpisode="handleClickEpisode"
    />
    <VideoControlList
      v-show="showVideoControlList"
      @tapList="showEpisodePanel = true"
    />
    <!-- 启动图层 -->
    <!--<div class="start-layout" v-show="showStartLayout"></div>-->
  </div>
</template>

<style scoped lang="scss">
.start-layout {
  position: absolute;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  background: #494949;
}

.index-page {
  position: absolute;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  background-color: black;
  background-image: url("@/assets/logo-gray.png");
  background-position: center;
  background-repeat: no-repeat;
}

.my-swipe {
  height: 100%;
}

:deep(.van-swipe-item) {
  position: relative;
}

.cover {
  position: absolute;
  max-width: 100%;
  max-height: 100%;
}
</style>
